<?php

class ExtuserController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/admin/column2';

	/**
	 * @return array action filters
	 */
	public function filters() {
            return array(
                array('auth.filters.AuthFilter'),
            );
        }

	public function actionImport()
        {
            $error = null;
            $extUser=array();
            if(isset($_POST["extuser"])&&$_FILES["file"]["error"]==0){
                if (($_FILES["file"]["type"] != "application/vnd.ms-excel")||($_FILES["file"]["size"] > 2000000)){
                    $error = "文件类型或大小不符合要求";
                }else{ 
                    $extuer = $_POST["extuser"];
                    $type = substr($_FILES["file"]["name"],1+strripos($_FILES["file"]["name"], "."));
                    if($type=="xlsx"){
                        $reader = PHPExcel_IOFactory::createReader('Excel2007');
                    }else{
                        $reader = PHPExcel_IOFactory::createReader('Excel5');
                    }
                    try {
                        $PHPExcel = $reader->load($_FILES["file"]["tmp_name"]); // 载入excel文件
                                            $sheet = $PHPExcel->getSheet(0); // 读取第一個工作表
                        $highestRow = $sheet->getHighestRow(); // 取得总行数
                        for($row = $extuer["startline"];$row<=$highestRow;$row++){
                            $realname = $sheet->getCell($extuer["realname"] . $row)->getValue();
                            $gender = $sheet->getCell($extuer["gender"] . $row)->getValue();
                            $age = $sheet->getCell($extuer["age"] . $row)->getValue();
                            $idcard_no = $sheet->getCell($extuer["idcard_no"] . $row)->getValue();
                            $married = $sheet->getCell($extuer["married"] . $row)->getValue();
                            $package_id = $sheet->getCell($extuer["package_id"] . $row)->getValue();
                            $u["realname"] = $realname;
                            $u["gender"] = $gender;
                            $u["age"] = $age;
                            $u["idcard_no"] = $idcard_no;
                            $u["married"] = $married;
                            $u["package_id"] = $package_id;
                            array_push($extUser, $u);
                        }

                    } catch (Exception $exc) {
                        $error = $exc->getMessage();
                    }
                }
            }
            $importinfo = null;
            if(isset($_POST["importuser"])){
                $importinfo["success"] = 0;
                $importinfo["failed"] = 0;
                $iuser = $_POST["importuser"];
                $ret = B2bExternalUser::model()->import($_POST["importuser"], $_POST["importuser"]["company_id"] ,$importinfo);
                if($ret!==TRUE){
                    $error = $ret;
                }
            }
//          $sheetData = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
            $ret = B2bCompany::model()->findAllByAttributes(array(),array("select"=>"id,name"));
            $this->render("import",array("company"=>$ret,"error"=>$error,"extuser"=>$extUser,"importinfo" => $importinfo));
        }

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new B2bExternalUser;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['B2bExternalUser']))
		{
			$model->attributes=$_POST['B2bExternalUser'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['B2bExternalUser']))
		{
			$model->attributes=$_POST['B2bExternalUser'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('B2bExternalUser');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new B2bExternalUser('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['B2bExternalUser']))
			$model->attributes=$_GET['B2bExternalUser'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return B2bExternalUser the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=B2bExternalUser::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param B2bExternalUser $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='b2b-external-user-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
